<?php

namespace wicked\process;

use wicked\core\Request;
use wicked\core\Response;
use wicked\core\Event;
use wicked\core\Forge;
use wicked\tools\Inflector;

class Builder extends Runnable
{

    public function run()
    {
        Event::fire('builder.start');

        // set view
        Response::layout(config('default::layout'));
        $template = Inflector::flatten(Response::controller()) . '/' . Inflector::flatten(Response::action());
        Response::template($template);

        // load controller
        $result = Forge::controller(Response::controller(), Response::action(), Response::args());

        if(is_null($result))
            Event::fire(404);
        else
            foreach($result as $key => $value)
                Response::data($key, $value);

        // load view
        if(Request::ajax())
            $this->content();
        else
            include path('app') . config('folder::layout') . '/' . Response::layout() . '.php';

        Event::fire('builder.end');
    }

    public function content()
    {
        Forge::template(Response::template(), Response::data());
    }

}
